package javawdw.security.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javawdw.security.dao.RoleResourceDao;
import javawdw.security.entity.Resource;
import javawdw.security.entity.Role;
import javawdw.security.entity.RoleResource;
import javawdw.security.spi.IList;
import javawdw.security.spi.IResult;
import javawdw.security.spi.IService;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sun.jersey.api.representation.Form;
import com.sun.jersey.spi.resource.Singleton;

@Singleton
@Path("/roleResource")
@Produces(MediaType.APPLICATION_JSON)
public class RoleResourceRs extends IService {
	private Map<String, Object> map = new HashMap<String, Object>();
	private static Logger logger = Logger.getLogger(RoleResourceRs.class);
	private RoleResourceDao roleResourceDao;

	@POST
	@Transactional(propagation = Propagation.REQUIRED)
	public IList find(Form form) {
		map.clear();
		String roleId = form.getFirst("roleId");
		if (roleId != null && !roleId.trim().equals("")) {
			map.put("role.id", roleId);
		}
		String resourceId = form.getFirst("resourceId");
		if (resourceId != null && !resourceId.trim().equals("")) {
			map.put("resource.id", resourceId);
		}
		List<RoleResource> list = roleResourceDao.find(map);
		logger.debug("查询角色-资源表");
		return new IList(list);
	}

	@POST
	@Path("saveOrUpdate")
	@Transactional(propagation = Propagation.REQUIRED)
	public String saveOrUpdate(@FormParam("roleId") String roleId,
			@FormParam("resourceId") String resourceId) {
		try {
			RoleResource roleResource = new RoleResource();
			Role role = new Role();
			role.setId(roleId);
			Resource resource = new Resource();
			resource.setId(resourceId);
			roleResource.setRole(role);
			roleResource.setResource(resource);
			this.roleResourceDao.saveOrUpdate(roleResource);
			return SUCCESS;
		} catch (Exception e) {
			return FAILURE;
		}
	}

	@POST
	@Path("delete")
	@Transactional(propagation = Propagation.REQUIRED)
	public IResult delete(String idsStr) {
		IResult iResult = new IResult();
		String[] ids = idsStr == null ? null : idsStr.split(",");
		if (ids != null && ids.length != 0) {
			for (String id : ids) {
				try {
					roleResourceDao.delete(id);
					iResult.addSuccess();
				} catch (Exception e) {
					e.printStackTrace();
					iResult.addFailure();
				}
			}
		}
		return iResult;
	}

	public void setRoleResourceDao(RoleResourceDao roleResourceDao) {
		this.roleResourceDao = roleResourceDao;
	}
}